package me.kennylee.tongji.service.impl;

import com.google.gson.Gson;
import me.kennylee.tongji.*;
import me.kennylee.tongji.builder.DistrictRptBuilder;
import me.kennylee.tongji.builder.TimeTrendRptBuilder;
import me.kennylee.tongji.builder.bean.DistrictRpt;
import me.kennylee.tongji.builder.bean.TimeTrendRpt;
import me.kennylee.tongji.response.ApiResponse;
import me.kennylee.tongji.response.SiteInfo;
import me.kennylee.tongji.response.SiteInfoList;
import me.kennylee.tongji.response.SiteListApiResponse;
import me.kennylee.tongji.service.ReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p> ReportService的实现类 </p>
 * <p>Created on 3/11/2017.</p>
 *
 * @author kennylee
 */
public class ReportServiceImpl implements ReportService {

    private final Config config;

    private static Logger logger = LoggerFactory.getLogger(ReportServiceImpl.class);

    public ReportServiceImpl(Config config) {
        super();
        this.config = config;
    }

    @Override
    public List<SiteInfo> getSiteList() throws IOException {
        ApiRequest request = new ApiRequest<>(AccountApiHeader.newInstance(config));
        String json = DataApiConnection.newInstance(GET_SITE_LIST_API_URL).post(request);
        Gson gson = GsonHelper.getBooleanAsIntGson();
        SiteListApiResponse response = gson.fromJson(json, SiteListApiResponse.class);
        List<SiteInfo> list = new ArrayList<>();
        if (isSuccess(response)) {
            for (SiteInfoList siteInfoList : response.getBody().getData()) {
                list.addAll(siteInfoList.getList());
            }
        }
        return list;
    }

    private boolean isSuccess(ApiResponse response) {
        return "success".equalsIgnoreCase(response.getHeader().getDesc());
    }

    /**
     * 地域访问
     *
     * @param reportDataParam 基础参数
     * @param metrics         指标。可为null，则使用方法内有默认的指标。
     * @return
     */
    @Override
    public ReportDataApiResponse getVisitDistrict(ReportDataParam reportDataParam, String metrics) {
        ReportDataApiMethod method = ReportDataApiMethod.VISIT_DISTRICT_A;
        String defaultMetrics = "pv_count,visitor_count,avg_visit_time";
        GetDataApiBody body = new GetDataApiBody.Builder(reportDataParam.getSiteId(), method,
                reportDataParam.getBeginDate(), reportDataParam.getEndDate(),
                metrics == null ? defaultMetrics : metrics).build();
        return sendData(body, null);
    }

    /**
     * 地域分布
     *
     * @param reportDataParam 基础参数
     * @return
     */
    @Override
    public ReportDataApiResponse<DistrictRpt> getDistrictRpt(ReportDataParam reportDataParam) {
        ReportDataApiMethod method = ReportDataApiMethod.OVERVIEW_DISTRICT_RPT;
        String metrics = "pv_count";
        GetDataApiBody body = new GetDataApiBody.Builder(reportDataParam.getSiteId(),
                method, reportDataParam.getBeginDate(), reportDataParam.getEndDate(), metrics).build();
        return sendData(body, DistrictRptBuilder.class);
    }

    /**
     * 趋势数据
     *
     * @param reportDataParam
     * @return
     */
    @Override
    public ReportDataApiResponse<TimeTrendRpt> getTimeTrendRpt(ReportDataParam reportDataParam) {
        ReportDataApiMethod method = ReportDataApiMethod.OVERVIEW_TIME_TREND_RPT;
        String metrics = "pv_count,visitor_count,ip_count,bounce_ratio,avg_visit_time";
        GetDataApiBody body = new GetDataApiBody.Builder(reportDataParam.getSiteId(),
                method, reportDataParam.getBeginDate(), reportDataParam.getEndDate(), metrics).build();
        return sendData(body, TimeTrendRptBuilder.class);
    }

    /**
     * 发送api请求
     *
     * @param body 请求参数
     * @return ReportDataApiResponse
     */
    private <M> ReportDataApiResponse<M> sendData(ApiBody body, Class<? extends ReportDataItemBuilder<M>> builderClass) {
        ApiRequest request = new ApiRequest<>(AccountApiHeader.newInstance(config), body);
        ReportDataApiResponse<M> response = null;
        try {
            String json = DataApiConnection.newInstance(GET_DATA_API_URL).post(request);
            response = ReportDataApiResponse.newInstance(json, builderClass);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return response;
    }
}
